package middleware

import (
	"fmt"
	"net/http"

	"github.com/gogf/gf/text/gstr"
)

const (
	allowOrigin                = "Access-Control-Allow-Origin"
	allOrigins                 = "*"
	allowCredentials           = "Access-Control-Allow-Credentials"
	allowCredentialsTrue       = "true"
	allowMethods               = "Access-Control-Allow-Methods"
	allowHeaders               = "Access-Control-Allow-Headers"
	headers                    = "Content-Type, Content-Length, Origin,Authorization,X-Requested-With,sst"
	methods                    = "GET, HEAD, POST, PATCH, PUT, DELETE , OPTIONS"
	accessControlExposeHeaders = "Access-Control-Expose-Headers"
	ExposeHeaders              = "nt,sst"
)

type CrosMiddleware struct {
}

func NewCrosMiddleware() *CrosMiddleware {
	return &CrosMiddleware{}
}

func (m *CrosMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		org := r.Header.Get("Origin")
		fmt.Println("org:", org)
		w.Header().Set(allowOrigin, org)
		w.Header().Set(allowMethods, methods)
		w.Header().Set(allowHeaders, headers)
		w.Header().Set(allowCredentials, allowCredentialsTrue)
		w.Header().Set(accessControlExposeHeaders, ExposeHeaders)
		method := gstr.ToLower(r.Method)
		if method == "options" {
			w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
			w.WriteHeader(http.StatusNoContent)
			return
		}
		next(w, r)
	}
}
